﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Editor;
using ESRI.ArcGIS.EditorExt;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.GlobeCore;
using ESRI.ArcGIS.NetworkAnalysis;
using ESRI.ArcGIS.Output;
using ESRI.ArcGIS.SystemUI;
using System.Windows.Forms;
using DIWAGIS.Modules;
using ESRI.ArcGIS.Carto;
using System.Data.SqlClient;
using System.IO;
using System.Data;
namespace DIWAGIS.Class
{
    class general_Model
    {
        public Boolean loadDataIntoForm(Control myForm, IFeature dataTable)
        {
            int indexField;
            string str;
            foreach (Control control in myForm.Controls)
            {
                indexField = dataTable.Fields.FindField(control.Name);
                
                if (control is TextBox|| control is RichTextBox)
                {
                    if (indexField >= 0) {
                        control.Text = dataTable.get_Value(indexField).ToString();
                    }
                }

                if (control is ComboBox)
                {
                    if (indexField >= 0)
                        {
                            ComboBox cbb;
                            cbb = (ComboBox)control;
                            cbb.SelectedValue = dataTable.get_Value(indexField).ToString();
                        }
                  
                }

                if (control is DateTimePicker)
                    {
                        //DateTimePicker date;
                        //date = (DateTimePicker)control;

                        //date.Text =(dataTable.get_Value(indexField).ToString());
                        if (indexField >= 0)
                            {


                                DateTimePicker date;
                                DateTime dat;
                                date = (DateTimePicker) control;
                                str = dataTable.get_Value(indexField).ToString();

                                if (str.Trim().Length > 0)
                                    {
                                        dat = DateTime.Parse(str);
                                        date.Checked = true;
                                        date.Value = dat;
                                    }
                                else
                                    {
                                        date.Checked = false;
                                    }
                            }
                    }


                if (control is GroupBox || control is TabControl || control is TabPage)
                {
                    loadDataIntoForm(control, dataTable);
                }
            }

            return true;
        }

        /// <summary>
        /// Cập nhật dữ liệu cho Feature 
        /// </summary>
        /// <param name="myForm">Form chứa dữ liệu</param>
        /// <param name="dataTable">Feature sẽ được cập nhật dữ liệu</param>
        /// <returns>True nếu đúng , False nếu có lỗi</returns>

        public void setDataIntoDatatable(Control myForm, IFeature dataTable)
        {
          
                int indexField;
                string str;
                int index = 0;
                //process.Maximum = myForm.Controls.Count;

                foreach (Control control in myForm.Controls)
                {
                    indexField = dataTable.Fields.FindField(control.Name);

                    if (control is TextBox || control is RichTextBox)
                        {
                            if (indexField >= 0)
                                {
                                    str = control.Text;
                                    if (str.Trim().Length > 0)
                                        {
                                            dataTable.set_Value(indexField, str);
                                        }
                                    else
                                        {
                                            dataTable.set_Value(indexField, null);
                                        }
                                }
                        }



                    if (control is ComboBox)
                    {
                        if (indexField >= 0)
                            {
                                ComboBox cbb;
                                cbb = (ComboBox) control;
                                if (cbb.SelectedValue != null)
                                    {
                                        dataTable.set_Value(indexField, cbb.SelectedValue);
                                    }
                                else
                                    {
                                        dataTable.set_Value(indexField, null);
                                    }
                            }
                    }

                    if (control is DateTimePicker)
                    {
                        if (indexField >= 0)
                            {
                                var date = (DateTimePicker) control;
                                if (date.Value != null)//always true
                                    {
                                        dataTable.set_Value(indexField, date.Value);
                                    }
                            }
                    }
                    index++;
                    //process.Value = index;
                   

                        if (control is GroupBox || control is TabControl || control is TabPage)
                        {
                            setDataIntoDatatable(control, dataTable);
                        }


                    }

      
            
        }
        public Boolean saveDataIntoDatabase(Control myForm, IFeature dataTable)
        {
            /// bắt đầu chỉnh sửa
            //IWorkspaceEdit pWorkSpaceEdit;
            //pWorkSpaceEdit = generalVariable.ICurrentWorkspace as IWorkspaceEdit;
            //pWorkSpaceEdit.StartEditing(true);
            //pWorkSpaceEdit.StartEditOperation();

            // bắt đầu gán giá trị
            int indexField;

            foreach (Control control in myForm.Controls)
            {
                indexField = dataTable.Fields.FindField(control.Name);

                if (control is TextBox)
                {
                    dataTable.set_Value(indexField, control.Text);
                }

                if (control is ComboBox)
                {
                    ComboBox cbb;
                    cbb = (ComboBox)control;
                    dataTable.set_Value(indexField, cbb.SelectedValue);
                }

                if (control is GroupBox || control is TabControl || control is TabPage)
                {
                    saveDataIntoDatabase(control, dataTable);
                }

            }

            ///////////// Lưu dữ liệu
            //dataTable.Store();
            //pWorkSpaceEdit.StopEditOperation();
            //pWorkSpaceEdit.StopEditing(true);
            //pWorkSpaceEdit = null;
            /////refesh
            generalVariable.mapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewAll, null, null);

            return true;
            ///
        }

        public IFeature findFeatureInTable(ILayer layer, string where)
        {
            try
            {
                IFeatureLayer featureLayer;
                featureLayer = layer as IFeatureLayer;
                IActiveView activeView;
                IFeature pFeature;
                ISelectionSet pSelectionSet;

                activeView = generalVariable.pHookHelper.FocusMap as IActiveView;

                IFeatureSelection featureSelection = featureLayer as IFeatureSelection;

                // Set up the query
                IQueryFilter QueryFilter = new QueryFilterClass();
                QueryFilter.WhereClause = where;

                // Invalidate only the selection cache. Flag the original selection
                activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null);

                // Perform the selection
                featureSelection.SelectFeatures(QueryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                generalVariable.mapControl.MapScale = 2500;

                ICursor pCursor;

                pSelectionSet = featureSelection.SelectionSet;
                pSelectionSet.Search(null, false, out pCursor);
                IFeatureCursor fCursor;
                fCursor = pCursor as IFeatureCursor;

                pFeature = fCursor.NextFeature();
                return pFeature;
            }
            catch (Exception ex)
            {
                //generalVariable.writeLogFileError("general_Model", "findFeatureInTable", ex.Message);
                return null;
            }
        }

        public IFeature findFeatureInTable1(string namelayer, string where)
        {
            try
            {
                IFeatureLayer featureLayer;

                ILayer layer = null;

                for (int i = 0; i < generalVariable.mapControl.LayerCount - 1; i++)
                {
                    layer = generalVariable.mapControl.get_Layer(i);
                    if (layer.Name == namelayer)
                    {
                        break;
                    }
                }

                if (layer == null)                
                {

                    return null;
                }
                    featureLayer = layer as IFeatureLayer;
                    IActiveView activeView;
                    IFeature pFeature;
                    ISelectionSet pSelectionSet;

                    activeView = generalVariable.pHookHelper.FocusMap as IActiveView;

                    IFeatureSelection featureSelection = featureLayer as IFeatureSelection;

                    // Set up the query
                    IQueryFilter QueryFilter = new QueryFilterClass();
                    QueryFilter.WhereClause = where;

                    // Invalidate only the selection cache. Flag the original selection
                    activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null);

                    // Perform the selection
                    featureSelection.SelectFeatures(QueryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                    generalVariable.mapControl.MapScale = 2500;

                    ICursor pCursor;

                    pSelectionSet = featureSelection.SelectionSet;
                    pSelectionSet.Search(null, false, out pCursor);
                    IFeatureCursor fCursor;
                    fCursor = pCursor as IFeatureCursor;

                    pFeature = fCursor.NextFeature();
                    return pFeature;
               
            }
            catch (Exception ex)
            {
                //generalVariable.writeLogFileError("general_Model", "findFeatureInTable", ex.Message);
                return null;
            }
        }
        public byte[] GetByteArray(string picPath)
        {
            System.IO.FileStream fs = new System.IO.FileStream(picPath, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(fs);
            byte[] bt = reader.ReadBytes((int)fs.Length);
            reader.Close();
            fs.Close();
            return bt;
        }

        public string getExFileName(string tenFilePath)
        {
            string[] array;
            if ((tenFilePath.Length > 0))
            {
                array = tenFilePath.Split('.');
                return array[array.Length - 1];
            }
            else
            {
                return "";
            }

        }

        public bool ThucThiSQL(SqlCommand sqlCMD)
        {

            try
            {
                SqlConnection connect;
                connectionDB cn = new connectionDB();
                connect = cn.KetnoiADONet(generalVariable.server, generalVariable.database, generalVariable.username, generalVariable.password);
                connect.Open();

                sqlCMD.Connection = connect;
                sqlCMD.ExecuteNonQuery();

                connect.Close();
                return true;
            }
            catch
            {
                //MessageBox.Show("Loi ", generalVariable.nameProgram, MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }

        }


        public DataTable GetDataTable(string strSQL)
        {

            try
            {

                DataTable functionReturnValue = null;
                // ERROR: Not supported in C#: OnErrorStatement

                SqlConnection connect;
                connectionDB cn = new connectionDB();
                connect = cn.KetnoiADONet(generalVariable.server, generalVariable.database, generalVariable.username, generalVariable.password);
                SqlDataAdapter sda = new SqlDataAdapter(strSQL, connect);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                connect.Close();
                functionReturnValue = dt;
                return functionReturnValue;
            }
            catch
            {
                return null;
            }

        }

        public bool DeleteFileTemp(string FileName)
        {
            bool functionReturnValue = false;

            functionReturnValue = false;

            if (System.IO.File.Exists(FileName))
            {
                System.IO.File.Delete(FileName);

            }
            functionReturnValue = true;
            return functionReturnValue;


        }

        public string CreateDirTemp(string strDir)
        {
            string functionReturnValue = null;
            functionReturnValue = "";

            if (!Directory.Exists(strDir))
            {
                System.IO.Directory.CreateDirectory(strDir);
            }

            functionReturnValue = strDir;
            return functionReturnValue;

        }

        public void LoadDatatoGridView(string query, DataGridView DataGridView1)
        {

            DataTable dt = GetDataTable(query);



            if (((dt != null)))
            {
                if ((dt.Rows.Count > 0))
                {
                    DataGridView1.Enabled = true;
                    DataGridView1.Rows.Clear();
                    DataGridView1.Rows.Add(dt.Rows.Count);

                    int index = 0;

                    for (index = 0; index <= dt.Rows.Count - 1; index++)
                    {
                        DataGridView1.Rows[index].DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                        DataGridView1.Rows[index].Cells[0].Value = dt.Rows[index][0];
                        DataGridView1.Rows[index].Cells[1].Value = dt.Rows[index][1];
                        DataGridView1.Rows[index].Cells[2].Value = dt.Rows[index][2];
                        DataGridView1.Rows[index].Cells[3].Value = dt.Rows[index][3];
                        //string datetime1 = DateTime.Parse(dt.Rows[index][4]).ToString("MM/dd/yyyy");
                        DataGridView1.Rows[index].Cells[4].Value = dt.Rows[index][4];
                        //DataGridView1.Rows[index].Cells[6].Value = dt.Rows[index][6];

                    }

                }
                else
                {
                    DataGridView1.Enabled = false;
                }
            }
            else
            {
                DataGridView1.Enabled = false;
            }




        }

    }
}
